from common.utils.decorator import sql_wrapper
from common.utils.db import list_object, get, upsert, delete
from common.card_login_history.model import CardLoginHistory
from datetime import datetime, timedelta

@sql_wrapper
def get_cardLoginHistory(id):
    data = CardLoginHistory.query.filter(CardLoginHistory.id == id).first()
    if data:
        return {
            "id": id,
            "card_id": data.card_id,
            "login_time": data.login_time,
            "logout_time": data.logout_time
        }
    else : return {}

@sql_wrapper
def list_order(query_dct):
    return list_object(query_dct, CardLoginHistory)

@sql_wrapper
def log_card_history(info):
    if info["IsLogin"]:
        data = CardLoginHistory()
        data.card_id = int(info["CardId"])
        data.login_time = datetime.utcnow()
        data.save()
        return data
    else:
        data = CardLoginHistory.query.filter(CardLoginHistory.id == info["Id"]).first()
        if data:
            data.logout_time = datetime.utcnow()
            data.save()
            return data

@sql_wrapper
def get_card_login_history(query_dct):
    return list_object(query_dct, CardLoginHistory)
